package com.ld.rightsSystem.service.impl;

import com.ld.rightsSystem.Enum.ResponseEnum;
import com.ld.rightsSystem.dto.TUserDTO;
import com.ld.rightsSystem.exception.DBDataNotFoundException;
import com.ld.rightsSystem.filter.JwtRequestFilter;
import com.ld.rightsSystem.mapper.TRoleRepository;
import com.ld.rightsSystem.mapper.TUserRepository;
import com.ld.rightsSystem.mapper.TrUserRoleRepository;
import com.ld.rightsSystem.pojo.*;
import com.ld.rightsSystem.service.inf.TUserService;
import com.ld.rightsSystem.utils.Utils;
import com.ld.rightsSystem.vo.R;
import com.ld.rightsSystem.vo.TUserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author lhb
 * @since 2023-12-27
 */
@Service
public class TUserServiceImpl implements TUserService {

    @Autowired
    private TUserRepository tUserRepository;

    @Autowired
    private TrUserRoleRepository trUserRoleRepository;

    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Autowired
    private TRoleRepository tRoleRepository;

    /**
     * 添加用户
     * @param tUserDTO
     * @return
     */
    @Override
    public R addTUser(TUserDTO tUserDTO) {
        // 检查用户名是否存在
        Long userIdByUserName = tUserRepository.findUserIdByUserName(tUserDTO.getUserName());
        if(userIdByUserName != null){
            return new R().error(ResponseEnum.PARAMS_BINDING_ERROR,null);
        }

        TUser tUser = new TUser();
        BeanUtils.copyProperties(tUserDTO,tUser);
        tUser.setPassword(Utils.passwordEncrypt(tUserDTO.getPassword()));
        tUser.setCreateBy(jwtRequestFilter.userNameThreadLocal.get());
        tUserRepository.insert(tUser);

        // 保存用户-角色关联信息
        tUserDTO.getRoleIds().stream().forEach(id->{
            TRole tRole = tRoleRepository.findTRoleByRoleId(id);
            if(tRole != null){
                TrUserRole trUserRole = new TrUserRole(userIdByUserName,id);
                trUserRoleRepository.save(trUserRole);
            }
        });
        return new R().OK(null);
    }

    /**
     * 修改用户
     * @param tUserDTO
     * @return
     */
    @Override
    @Transactional
    public R editTUser(TUserDTO tUserDTO) throws DBDataNotFoundException {
        TUser tUserByUserIdAndUserName = tUserRepository.findTUserByUserIdAndUserName(tUserDTO.getUserId(), tUserDTO.getUserName());
        if(tUserByUserIdAndUserName == null){
            throw new DBDataNotFoundException();
        }
        BeanUtils.copyProperties(tUserDTO,tUserByUserIdAndUserName);
        tUserByUserIdAndUserName.setUpdateBy(jwtRequestFilter.userNameThreadLocal.get());
        tUserByUserIdAndUserName.setUpdateTime(new Date());
        tUserRepository.updateTUser(tUserByUserIdAndUserName);
        trUserRoleRepository.deleteTrUserRoleByUserId(tUserDTO.getUserId());
        // 保存用户-角色关联信息
        tUserDTO.getRoleIds().stream().forEach(id->{
            TRole tRole = tRoleRepository.findTRoleByRoleId(id);
            if(tRole != null){
                TrUserRole trUserRole = new TrUserRole(tUserDTO.getUserId(),id);
                trUserRoleRepository.save(trUserRole);
            }
        });
        return new R().OK(null);
    }

    /**
     * 分页查询用户
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public R getTUser(int pageNum, int pageSize) {
        PageRequest pageRequest = PageRequest.of(pageNum - 1,pageSize);
        List<TUser> tUsers = tUserRepository.findTUsersPageable(pageRequest);
        Map<String,List<TUser>> result = new HashMap<>();
        result.put("list",tUsers);
        return new R().OK(result);
    }



    /**
     * 根据id删除用户
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public R deleteTUserById(Long userId) throws DBDataNotFoundException {
        TUser tUserByUserId = tUserRepository.findTUserByUserId(userId);
        if (tUserByUserId != null){
            tUserRepository.deleteTUserByUserId(userId,jwtRequestFilter.userNameThreadLocal.get(),new Date());
            trUserRoleRepository.deleteTrUserRoleByUserId(userId);
            return new R().OK(null);
        }else {
            throw new DBDataNotFoundException();
        }
    }

    /**
     * 检查字段是否可用
     * @param checkUName
     * @return
     */
    @Override
    public R checkFieldAvailable(String checkUName) {
        Map<String,Boolean> result = new HashMap<>();
        if(checkUName.trim().length() > 0){
            TUser tUserByUserName = tUserRepository.findTUserByUserName(checkUName);
            if(tUserByUserName == null){
                result.put("checkUName",true);
            }else {
                result.put("checkUName",false);
            }
        }else {
            result.put("checkUName",false);
        }
        return new R().OK(result);
    }

    /**
     * 根据id查询用户信息
     * @param userId
     * @return
     */
    @Override
    public R findTUserById(Long userId) {
        TUser tUser = tUserRepository.findTUserByUserId(userId);
        TUserVO tUserVO = new TUserVO();
        BeanUtils.copyProperties(tUser,tUserVO);
        List<Long> roleIds = trUserRoleRepository.findRoleIdsByUserId(userId);
        tUserVO.setRoleIds(roleIds);
        HashMap<String, TUser> result = new HashMap<>();
        result.put("info",tUser);
        return new R().OK(result);
    }
}
